
#define GL_GLEXT_PROTOTYPES

#include "openglframe.h"
#include <algorithm>

OpenGLFrame::OpenGLFrame(QWidget* parent, const QGLWidget* shareWidget, Qt::WFlags f)
   : QGLWidget(parent, shareWidget, f), arcball(1,1) {
   
   // for keyboard use
   setFocusPolicy(Qt::StrongFocus);
   
   cursor3D = Point3(0,0,0);
   interactionMode = VIEW_MODE;
   
   texFloor = 0;
   
   fovy = 40.0;
   zoomFactor = 1.0;
   meshrendermode_mask = 0x20;
   
   isProjOrtho = true; // orthographic projection
   is_lightingOn = true;
   
   viewitems_mask = 0x0; 
   viewitems_mask = viewitems_mask | MODELDEF;
   viewitems_mask = viewitems_mask | SKELETONDEF;
   viewitems_mask = viewitems_mask | KEYPOINTS;
   viewitems_mask = viewitems_mask | CONSTRAINTS;
   viewitems_mask = viewitems_mask | FLOOR;
   viewitems_mask = viewitems_mask | INFO;
   
   // Floor and shadow specificacion
   floor[0] = Point3(-4.5,-1.0, 4.5);
   floor[1] = Point3( 4.5,-1.0, 4.5);
   floor[2] = Point3( 4.5,-1.0,-4.5);
   floor[3] = Point3(-4.5,-1.0,-4.5);
   pfloor = Plane3(floor[0], floor[2], floor[1]);
   
   float l[] = {0.0, 50.0, 20.0}; // Coordinates of the light source
   float e[] = {0.0, -0.99, 0.0}; // Point of the floor plane
   float n[] = {0.0, -1.0, 0.0}; // Normal vector for the plane
   createShadowProjectionMatrix(l,e,n);
   
   currentFrame = 0;
   
   nearplane  = 1.0;  farplane  =-1.0;
   leftplane  =-1.0; rightplane = 1.0;
   bottomplane=-1.0; topplane   = 1.0;
}

OpenGLFrame::~OpenGLFrame() {
   cout<<"::> ~GSkeleton()"<<endl;
}

void OpenGLFrame::initializeGL() {
   
   glEnable(GL_LIGHTING);
   glEnable(GL_LIGHT0);
   glEnable(GL_LIGHT1);
   glEnable(GL_DEPTH_TEST);
   glEnable(GL_NORMALIZE);
   
   // lighting setup
   //~ GLfloat left_light_position[] =  {0.0f, 50.0f, 50.0f, 0.0f};
   //~ GLfloat right_light_position[] = {0.0f, -50.0f, 50.0f, 0.0f};
   GLfloat left_light_position[] =  {0.0f, 20.0f, 25.0f, 0.0f};
   GLfloat right_light_position[] = {0.0f, -20.0f, 25.0f, 0.0f};
   GLfloat left_diffuse_light[] =  {1.0f, 1.0f, 1.0f, 1.0f};
   GLfloat right_diffuse_light[] = {1.0f, 1.0f, 1.0f, 1.0f};
   
   glLightfv(GL_LIGHT0, GL_POSITION, left_light_position);
   glLightfv(GL_LIGHT0, GL_DIFFUSE, left_diffuse_light);
   glLightfv(GL_LIGHT1, GL_POSITION, right_light_position);
   glLightfv(GL_LIGHT1, GL_DIFFUSE, right_diffuse_light);
   
   //simple orange
   //GLfloat mat_orange_diffuse[] = {0.9, 0.45, 0.0, 1.0};
   //GLfloat mat_specular[] = {0.7, 0.6, 0.6, 1.0};
   GLfloat mat_orange_diffuse[] = {0.9, 0.45, 0.0, 1.0};
   GLfloat mat_specular[] = {1.0, 1.0, 1.0, 1.0};
   GLfloat mat_shininess[] = {80.0};
   glMaterialfv(GL_FRONT, GL_DIFFUSE, mat_orange_diffuse);
   glMaterialfv(GL_FRONT, GL_SPECULAR, mat_specular);
   glMaterialfv(GL_FRONT, GL_SHININESS, mat_shininess);
   
   // sky blue
   //~ GLfloat mat_orange_diffuse[] = {0.25, 0.45, 0.9, 1.0};
   //~ GLfloat mat_specular[] = {0.633, 0.727811, 0.633, 1.0};
   //~ GLfloat mat_shininess[] = {76.8};
   //~ glMaterialfv(GL_FRONT, GL_DIFFUSE, mat_orange_diffuse);
   //~ glMaterialfv(GL_FRONT, GL_SPECULAR, mat_specular);
   //~ glMaterialfv(GL_FRONT, GL_SHININESS, mat_shininess);
   
   // verde
   //~ GLfloat amb[4] = {0.0215f, 0.1745f, 0.0215f, 0.55f};
   //~ GLfloat dif[4] = {0.07568f, 0.61424f, 0.07568f, 0.55f};
   //~ GLfloat spe[4] = {0.633f, 0.727811f, 0.633f, 0.55f};
   //~ GLfloat shi[1] = {76.8f};
   
   // rosado
   //~ GLfloat amb[4] = {0.0215f, 0.1745f, 0.0215f, 0.55f};
   //~ GLfloat dif[4] = {1-0.07568f, 1-0.61424f, 1-0.07568f, 0.55f};
   //~ GLfloat spe[4] = {0.633f, 0.727811f, 0.633f, 0.55f};
   //~ GLfloat shi[1] = {76.8f};
   
   // azul
   //~ GLfloat amb[4] = {0.33, 0.22, 0.03, 1.0};
   //~ GLfloat dif[4] = {1-0.78, 1-0.57, 1-0.11, 0.6};
   //~ GLfloat spe[4] = {0.99, 0.91, 0.81, 1.0};
   //~ GLfloat shi[1] = {27.8};
   
   // gold
   //~ GLfloat amb[4] = {0.24725f, 0.1995f, 0.0745f, 1.0};
   //~ GLfloat dif[4] = {0.75164f, 0.60648f, 0.22648f, 1.0};
   //~ GLfloat spe[4] = {0.928281f, 0.855802f, 0.666065f, 1.0};
   //~ GLfloat shi[1] = {51.2};
   
   //~ glMaterialfv(GL_FRONT, GL_AMBIENT,   amb);
   //~ glMaterialfv(GL_FRONT, GL_DIFFUSE,   dif);
   //~ glMaterialfv(GL_FRONT, GL_SPECULAR,  spe);
   //~ glMaterialfv(GL_FRONT, GL_SHININESS, shi);
   
   glClearColor(1,1,1,1);
   glColor4f(1,1,0,1);
   meshrendermode_mask = SMOOTH;
   sceneT.identity();
   
   std::time(&start);
   frame = 0;
   
   genWorldLimits();
   
   //~ texFloor = new Texture("icons/floor4.png", GL_TEXTURE_2D);
   //~ spriteTexCtlPoint = Texture("icons/redballT.png", GL_TEXTURE_2D);
   
   //~ kernel_xray.vertex_source("xray.vert");
   //~ kernel_xray.fragment_source("xray.frag");
   //~ kernel_xray.install(false);
   //~ kernel_xray.use(true);
   //~ kernel_xray.set_uniform("edgefalloff", 1.0f); 
   //~ kernel_xray.use(false);
   
   //~ setGLview();
}

void OpenGLFrame::fpsInfo() {
   
   // Render info
   if ((viewitems_mask & INFO) == INFO) {
      glDisable(GL_LIGHTING);
      glDisable(GL_DEPTH_TEST);
      
      frame++;
      std::time(&end);
      double ddifftime = std::difftime(end, start);
      if (ddifftime > 1) {
         cfps = frame/ddifftime;
         start = end;
         frame = 0;
      }
      
      QString strInfoFPS=QString("FPS: %1").arg(cfps,7,'f',1);
      
      glColor4f(0.0, 0.0, 0.0, 1.0);
      renderText(30,75, strInfoFPS);
      
      glEnable(GL_LIGHTING);
      glEnable(GL_DEPTH_TEST);
   }
}

void OpenGLFrame::drawFloor() {
   
   glEnable(GL_TEXTURE_2D);
   texFloor->bind();
   
   glDisable(GL_LIGHTING);
   glPolygonMode(GL_FRONT, GL_FILL);
   glPolygonMode(GL_BACK, GL_LINE);
   glColor3f(1.0,1.0,1.0);
   glBegin(GL_QUADS);
   glNormal3f(0.0,1.0,0.0);
   glTexCoord2d(0.0,0.0); glVertex3f(floor[0][0],floor[0][1], floor[0][2]);
   glTexCoord2d(1.0,0.0); glVertex3f(floor[1][0],floor[1][1], floor[1][2]);
   glTexCoord2d(1.0,1.0); glVertex3f(floor[2][0],floor[2][1], floor[2][2]);
   glTexCoord2d(0.0,1.0); glVertex3f(floor[3][0],floor[3][1], floor[3][2]);
   glEnd();
   glEnable(GL_LIGHTING);
   glPolygonMode(GL_FRONT_AND_BACK, GL_FILL);
   
   glDisable(GL_TEXTURE_2D);
}

void OpenGLFrame::createShadowProjectionMatrix(float *l, float *e, float *n) {
   
   // These are c and d (corresponding to the tutorial)
   float d = n[0]*l[0] + n[1]*l[1] + n[2]*l[2];
   float c = e[0]*n[0] + e[1]*n[1] + e[2]*n[2] - d;
   
   // Create the matrix. OpenGL uses column by column ordering
   shadowMatrix[0]  = l[0]*n[0]+c;
   shadowMatrix[4]  = n[1]*l[0];
   shadowMatrix[8]  = n[2]*l[0];
   shadowMatrix[12] = -l[0]*c-l[0]*d;
  
   shadowMatrix[1]  = n[0]*l[1];
   shadowMatrix[5]  = l[1]*n[1]+c;
   shadowMatrix[9]  = n[2]*l[1];
   shadowMatrix[13] = -l[1]*c-l[1]*d;
  
   shadowMatrix[2]  = n[0]*l[2];
   shadowMatrix[6]  = n[1]*l[2];
   shadowMatrix[10] = l[2]*n[2]+c;
   shadowMatrix[14] = -l[2]*c-l[2]*d;
  
   shadowMatrix[3]  = n[0];
   shadowMatrix[7]  = n[1];
   shadowMatrix[11] = n[2];
   shadowMatrix[15] = -d;
}

void OpenGLFrame::genWorldLimits(Point3 center, Number radius) {
   
   /*
   if (skeleton != 0) {
      //~ mincoo[0] = skeleton->minPoint[0]; mincoo[1] = skeleton->minPoint[1]; mincoo[2] = skeleton->minPoint[2];
      //~ maxcoo[0] = skeleton->maxPoint[0]; maxcoo[1] = skeleton->maxPoint[1]; maxcoo[2] = skeleton->maxPoint[2];
   }
   else {
      mincoo[0] = -1; mincoo[1] = -1; mincoo[2] = -1;
      maxcoo[0] =  1; maxcoo[1] =  1; maxcoo[2] =  1;
   }
   */
   
   
   mincoo[0] = -1; mincoo[1] = -1; mincoo[2] = -1;
   maxcoo[0] =  1; maxcoo[1] =  1; maxcoo[2] =  1;
   
   float xc = mincoo[0] + 0.5*(maxcoo[0]-mincoo[0]);
   float yc = mincoo[1] + 0.5*(maxcoo[1]-mincoo[1]);
   
   float WorldWidth  = abs(maxcoo[0]-mincoo[0]);
   float WorldHeight = abs(maxcoo[1]-mincoo[1]);
   
   if ((WorldHeight/WorldWidth) > ((float)height()/(float)width())) {
      WorldWidth = WorldHeight / ((float)height()/(float)width());
   }
   else if ((WorldHeight/WorldWidth) < ((float)height()/(float)width())) {
      WorldHeight = WorldWidth * ((float)height()/(float)width());
   }
   
   // world limits
   mincoo[0] = xc - 0.5*WorldWidth;
   mincoo[1] = yc - 0.5*WorldHeight;
   
   maxcoo[0] = xc + 0.5*WorldWidth;
   maxcoo[1] = yc + 0.5*WorldHeight;
   
   // center camera
   camcenter[0] = xc;
   camcenter[1] = yc;
   camcenter[2] = mincoo[2] + 0.5*(maxcoo[2]-mincoo[2]);
   
   
   /// //////////
   
   //~ // the camera points to
   //~ camcenter[0] = center.x();
   //~ camcenter[1] = center.y();
   //~ camcenter[2] = center.z();
   
   //~ // the camera position
   //~ cameye[0] = camcenter[0];
   //~ cameye[1] = camcenter[1];
   //~ cameye[2] = 2.0*radius;
   
   //~ nearplane = radius;
   //~ farplane = nearplane + 2.0*radius;
   //~ leftplane = -radius;
   //~ rightplane = radius;
   //~ bottomplane = -radius;
   //~ topplane = radius;
   
   //~ GLdouble aspect = (GLdouble)width()/(GLdouble)height();
   //~ if (aspect < 1.0) { // window taller than wide
      //~ bottomplane /= aspect;
      //~ topplane /= aspect;
   //~ }
   //~ else {
      //~ leftplane *= aspect;
      //~ rightplane *= aspect;
   //~ }
}

/// It sets the projection/modelview matrices
void OpenGLFrame::setGLview() {
   
   glMatrixMode(GL_PROJECTION);
   glLoadIdentity();
   
   WorldWidth  = abs(maxcoo[0]-mincoo[0])*0.5;
   WorldHeight = abs(maxcoo[1]-mincoo[1])*0.5;
   
   objDistance = 0.8660*(maxcoo[1]-mincoo[1]); /// sqrt(3)/2 = 0.8660
   ////~ objDistance = WorldHeight;
   nearplane = objDistance - objDistance*0.5;
   farplane  = nearplane + 20.0;
   
   cameye[0] = camcenter[0];
   cameye[1] = camcenter[1];
   cameye[2] = maxcoo[2] + objDistance;
   
   if (isProjOrtho)
      glOrtho(-WorldWidth*zoomFactor,  WorldWidth*zoomFactor, 
              -WorldHeight*zoomFactor, WorldHeight*zoomFactor, 
               nearplane, farplane);
   else 
      gluPerspective(fovy*zoomFactor, (GLfloat)width()/(GLfloat)height(), nearplane, farplane);
   
   glMatrixMode(GL_MODELVIEW);
   glLoadIdentity();
   glViewport(0, 0, width(), height());
}

/*
void OpenGLFrame::setGLview() {
   
   glMatrixMode(GL_PROJECTION); 
   glLoadIdentity(); 
   //~ if (isProjOrtho)
      //~ glOrtho(-WorldWidth*zoomFactor,  WorldWidth*zoomFactor, 
              //~ -WorldHeight*zoomFactor, WorldHeight*zoomFactor, 
               //~ nearplane, farplane);
   //~ else 
      //~ gluPerspective(fovy*zoomFactor, (GLfloat)width()/(GLfloat)height(), nearplane, farplane);
   glOrtho(leftplane, rightplane, bottomplane, topplane, nearplane, farplane);
   
   glMatrixMode(GL_MODELVIEW);
   glLoadIdentity();
   glViewport(0, 0, width(), height());
}
*/

/// A simple resize callback.
/// @param width the width of the new window.
/// @param height the height of the new window.
void OpenGLFrame::resizeGL(int width, int height) {
   
   setGLview();
   arcball.setBounds(width, height);  //Update mouse bounds for the arcball
}

/// Callback for handling mouse button press.
/// @param event encapsulates the event's info.
void OpenGLFrame::mousePressEvent(QMouseEvent *event) {
   
   xini=event->x(); yini=height()-event->y();
   if (event->button() == Qt::MidButton) {
      arcball.click(xini,yini);
   }
   else if (event->button() == Qt::RightButton) {
      grabLast = grabStart = screenToWorld(xini, yini);
   }
   sceneIniT = sceneT;
   cameyeI[0] = cameye[0];
   cameyeI[1] = cameye[1];
   cameyeI[2] = cameye[2];
   glDraw();
}

/// Callback for handling mouse movements.
/// @param event encapsulates the event's info.
void OpenGLFrame::mouseMoveEvent(QMouseEvent *event) {
   
   if ((event->buttons() & Qt::MidButton)) { // rotations handler
      AMatrix<float> mT;
      arcball.drag(event->x(), height()-event->y(), &mT);
      sceneT = mT*sceneIniT;
      
      //~ AMatrix<float> mT;
      //~ arcball.drag(event->x(), height()-event->y(), &mT);
      //~ Vector3 v(cameyeI[0]-camcenter[0],cameyeI[1]-camcenter[1],cameyeI[2]-camcenter[2]);
      //~ float vp[3];
      //~ vp[0] = mT[0]*v[0] + mT[1]*v[1] + mT[2]*v[2];
      //~ vp[1] = mT[4]*v[0] + mT[5]*v[1] + mT[6]*v[2];
      //~ vp[2] = mT[8]*v[0] + mT[9]*v[1] + mT[10]*v[2];
      //~ cameye[0] = camcenter[0] + vp[0];
      //~ cameye[1] = camcenter[1] + vp[1];
      //~ cameye[2] = camcenter[2] + vp[2];
   }
   else if (event->buttons() & Qt::RightButton) { // translations handler
      Vector3 t = screenToWorld(xini, yini, event->x(), height()-event->y());
      AMatrix<float> mT;
      mT.identity();
      mT.translation(t[0], t[1], t[2]);
      sceneT = sceneIniT*mT;
   }
   glDraw();
}

/// Callback for handling mouse button release.
/// @param event encapsulates the event's info.
void OpenGLFrame::mouseReleaseEvent(QMouseEvent *event) {
   
   switch (interactionMode) {
      case SELECT_JOINTS_MODE: {
         break;
      }
      case VIEW_MODE: {
         break;
      }
   }
   event->accept();
   glDraw();
}

/// Inplements zoom operations using the mouse wheel
void OpenGLFrame::wheelEvent(QWheelEvent *e) {
   
   //~ if (e->delta()>0) zoomFactor+= 0.1;
   //~ else              zoomFactor-= 0.1;
   //~ e->accept(); 
   //~ setGLview();
   //~ glDraw();
   
   if (e->delta()>0) zoomIn();
   else              zoomOut();
      
   e->accept();
}

void OpenGLFrame::keyPressEvent(QKeyEvent *event) {
   
   if (event->key() == Qt::Key_Escape) {
      exit(0);
   }
}

/// Implements the "zoomin" operation
void OpenGLFrame::zoomIn () {
   
   AMatrix<float> mT;
   mT.identity();
   mT.scaling(1.2);
   sceneT = mT*sceneT;
   
   glDraw();
}

/// Implements the "zoomout" operation
void OpenGLFrame::zoomOut () {
   
   AMatrix<float> mT;
   mT.identity();
   mT.scaling(1.0/1.2);
   sceneT = mT*sceneT;
   
   glDraw();
}

/// Implements the "zoomall" operation
void OpenGLFrame::zoomAll () {
   
   sceneT.identity();
   glDraw();
}

/// Returns the world coordinates of a point in screen space
Point3 OpenGLFrame::screenToWorld(int x, int y) {
   
   glGetIntegerv(GL_VIEWPORT, viewport);
   glGetDoublev(GL_PROJECTION_MATRIX, pMtx);
   glGetDoublev(GL_MODELVIEW_MATRIX, mMtx);
   
   GLdouble xw, yw, zw;
   gluUnProject(x, y, 1.0, mMtx, pMtx, viewport, &xw, &yw, &zw);
   return Point3(xw, yw, zw);
}

/// Returns the translation vector in world coordinates of two points in screen space
Vector3 OpenGLFrame::screenToWorld(int xi, int yi, int xe, int ye) {
   
   glGetIntegerv(GL_VIEWPORT, viewport);
   //~ glGetDoublev(GL_PROJECTION_MATRIX, pMtx);
   glGetDoublev(GL_MODELVIEW_MATRIX, mMtx);
   
   /// Compute the world coordinates using the orthographic projection
   glMatrixMode(GL_PROJECTION);
   glPushMatrix();
   glLoadIdentity();
   glOrtho(-WorldWidth*zoomFactor,  WorldWidth*zoomFactor, 
           -WorldHeight*zoomFactor, WorldHeight*zoomFactor, 
            nearplane, farplane);
   glGetDoublev(GL_PROJECTION_MATRIX, pMtx);
   glPopMatrix();
   
   GLdouble ws[3], we[3]; // project on the near plane
   gluUnProject(xi, yi, 0, mMtx, pMtx, viewport, &ws[0], &ws[1], &ws[2]);
   gluUnProject(xe, ye, 0, mMtx, pMtx, viewport, &we[0], &we[1], &we[2]);
   
   return Vector3(we[0]-ws[0], we[1]-ws[1], we[2]-ws[2]);
}

Vector3 OpenGLFrame::getTranslationWorld(int x, int y, int xlastt, int ylastt) {
   
   glGetDoublev(GL_MODELVIEW_MATRIX, mMtx);
   glGetDoublev(GL_PROJECTION_MATRIX, pMtx);
   glGetIntegerv(GL_VIEWPORT, viewport);
   
   GLdouble m[]={1,0,0,0,
              0,1,0,0,
              0,0,1,0,
              0,0,0,1};
   
   double wbx, wby, wbz, wex, wey, wez;
   gluUnProject(xlastt, ylastt, 0.0, mMtx, pMtx, viewport, &wbx, &wby, &wbz);
   gluUnProject(x, y, 0.0, mMtx, pMtx, viewport, &wex, &wey, &wez);
   return Vector3(wex-wbx, wey-wby, wez-wbz);
   
   //~ gluUnProject(xlast, ylast, 0.0, m, pMtx, viewport, &wbx, &wby, &wbz);
   //~ gluUnProject(x, y, 0.0, m, pMtx, viewport, &wex, &wey, &wez);
   //~ return Vector(wex-wbx, wey-wby, 0);
}

void OpenGLFrame::animateFrame(int animIndex) {
   
   if(animIndex<0)   currentFrame = 0;
   else              currentFrame = animIndex;
   
//   for (unsigned i=0; i<animators.size(); ++i) {
//      animators[i]->frame(animIndex);
//   }
   glDraw();
}
